package com.hxy.springcloud.controller;

import com.hxy.springcloud.pojo.Department;
import com.hxy.springcloud.service.DepartmentService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;


@RestController
public class DepartnentController {
    @Autowired
    private DepartmentService departmentService;

    @PostMapping("/dept/add")
    public boolean addDepartment(Department department) {
        return departmentService.addDepartment(department);
    }

    @GetMapping("/dept/queryById/{id}")
    //设置服务失败时调用的方法，熔断机制
    @HystrixCommand(fallbackMethod = "hystrixQueryDepartmentById")
    public Department queryDepartmentById(@PathVariable("id") long id) {
        Department department = departmentService.queryDepartmentById(id);
        if (department==null){
            throw new RuntimeException("id:" + id + " 的用户不存在或信息查找失败！");
        }
        return department;
    }

    /**
     * 服务熔断：配置在服务端，表现为某个服务请求超时或异常时，引起熔断机制，进入熔断方法，作用类似于一个保险丝
     *
     * 服务降级：配置在客户端，从整个网站的请求负载考虑，当某个服务熔断或关闭后，该服务将不再被调用，
     * 此时在客户端，我们可以准备一个FallbackFactory，返回一个默认的缺省值
     * 服务降级会造成整体的服务水平下降，但是保证了其他服务可用。
     * 用于在某一时间服务请求数量过大时，关掉一些不重要或访问少的服务，以确保负载大的服务可以顺利进行，
     */

    //熔断方法
    public Department hystrixQueryDepartmentById(@PathVariable("id") long id) {
        Department tempDepartment = new Department()
                .setDepartId(id)
                .setDName("id:" + id + " 的用户不存在或信息查找失败！")
                .setDb_source("no this database in MySQL");
        return tempDepartment;
    }

    @GetMapping("/dept/queryAll")
    public List<Department> queryAllDepartment() {
        List<Department> list = departmentService.queryAllDepartment();
        return list;
    }

}
